package com.core.image.tcp;

import com.core.image.core.Connector;
import com.core.image.core.box.StringRecevicePacket;
import com.core.image.handler.ConnectorStringPacketChain;
import com.core.image.utils.ByteUtils;
import com.core.image.utils.CloseUtils;
import com.core.image.utils.Foo;
import com.sun.org.apache.xml.internal.resolver.readers.ExtendedXMLCatalogReader;

import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SocketChannel;

/**
 * describe:
 *
 * @author 库琦
 * @date 2020/01/21
 */
public class TCPClient extends ConnectorHandler {


    public TCPClient(SocketChannel socket,File cachePath) throws Exception{
        super(socket,cachePath);
        getStringPacketChain().appendLast(new PrintStringPacketChain());
    }
    private class PrintStringPacketChain extends ConnectorStringPacketChain {
        @Override
        public boolean consume(ConnectorHandler clientHandler, StringRecevicePacket packet) {
            String str = packet.entity();
            return true;
        }
    }
    public void close(){
        CloseUtils.close(this);
    }
    @Override
    public void onChannelClosed(SocketChannel channel) {
        super.onChannelClosed(channel);
    }

     static TCPClient linkWith(ServerInfo serverInfo,File cachePath)throws IOException{
        SocketChannel socket =SocketChannel.open();
        try {
            socket.connect(new InetSocketAddress(InetAddress.getByName(serverInfo.getAddress()),serverInfo.getPort()));
            System.out.println("已发起服务器连接，并进入后续流程～");
            System.out.println("客户端信息：" + socket.getLocalAddress().toString());
            System.out.println("服务器信息：" + socket.getRemoteAddress().toString());

            return  new TCPClient(socket,cachePath);
        }catch (Exception e){
            e.printStackTrace();
            CloseUtils.close(socket);

        }
            return null;
    }


}
